package com.sskj.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sskj.api.domain.ProductCapability;
import com.sskj.api.domain.ProductCapabilityMapping;
import com.sskj.api.mapper.ProductCapabilityMappingMapper;
import com.sskj.api.service.IProductCapabilityMappingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class ProductCapabilityMappingService extends ServiceImpl<ProductCapabilityMappingMapper, ProductCapabilityMapping> implements IProductCapabilityMappingService {

    @Override
    @Transactional
    public void add(Long productId, List<Long> capabilityIds) {
        LambdaQueryWrapper<ProductCapabilityMapping> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ProductCapabilityMapping::getProductId, productId);
        remove(lambdaQueryWrapper);

        if (capabilityIds != null && !capabilityIds.isEmpty()) {
            List<ProductCapabilityMapping> productCapabilityMappingList = new ArrayList<>();
            for (Long capabilityId : capabilityIds) {
                ProductCapabilityMapping productCapabilityMapping = new ProductCapabilityMapping();
                productCapabilityMapping.setCapabilityId(capabilityId);
                productCapabilityMapping.setProductId(productId);
                productCapabilityMapping.setCreateTime(LocalDateTime.now());

                productCapabilityMappingList.add(productCapabilityMapping);
            }

            saveBatch(productCapabilityMappingList);
        }
    }

    @Override
    public List<ProductCapability> listCapability(Long productId) {
        return baseMapper.listCapabilityByProductId(productId);
    }
}
